package com.msw.http;

import com.google.common.base.Joiner;
import com.google.common.collect.Lists;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;

/**
 * down source jar from mavenCenter:
 * <br/>
 * https://repo1.maven.org/maven2/org/springframework/spring-web/4.2.4.RELEASE/spring-web-4.2.4.RELEASE-sources.jar
 *
 * Created by hadoop on 17-7-29.
 */
public class DownFile {

    private static final String baseUrl = "http://repo1.maven.org/maven2";

    public static final String baseDir = "/home/hadoop/.m2/repository";

    /**
     * 从网络Url中下载文件
     * @param urlStr
     * @param fileName
     * @param savePath
     * @throws IOException
     */
    public static void  downLoadFromUrl(String urlStr,String fileName,String savePath) throws IOException {
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        //设置超时间为3秒
        conn.setConnectTimeout(3*1000);
        //防止屏蔽程序抓取而返回403错误
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

        //得到输入流
        InputStream inputStream = conn.getInputStream();
        //获取自己数组
        byte[] getData = readInputStream(inputStream);

        //文件保存位置
        File saveDir = new File(savePath);
        if(!saveDir.exists()){
            saveDir.mkdir();
        }
        File file = new File(saveDir+File.separator+fileName);
        if (!file.exists()) {
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(getData);
            if(fos!=null){
                fos.close();
            }
        }
        if(inputStream!=null){
            inputStream.close();
        }
    }



    /**
     * 从输入流中获取字节数组
     * @param inputStream
     * @return
     * @throws IOException
     */
    public static  byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }


    public static List<JarVo> readJars() {
        List<JarVo> list = Lists.newArrayList();
        String base = System.getProperty("user.dir");
        try {
            Files.readAllLines(Paths.get(base, "doc", "dependency.txt")).parallelStream()
                    .filter(l -> l.contains("org.springframework"))
                    .map(l -> {
                        int index = l.indexOf("org");
                        return l.substring(index);
                    }).forEach(l -> {
                String[] attr = l.split(":");
                JarVo vo = new JarVo(attr[0], attr[1], attr[3]);
                list.add(vo);
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }


    /**
     * create downloaded url
     *
     * @param jarVo
     * @return
     */
    public static String createUrl(JarVo jarVo) {
        String filename = jarVo.getAtifactId() + "-" + jarVo.getVersion() + "-sources.jar";
        List<String> parties = Lists.newArrayList(baseUrl);
        parties.addAll(Arrays.asList(jarVo.getGroupId().split("\\.")));
        parties.add(jarVo.getAtifactId());
        parties.add(jarVo.getVersion());
        parties.add(filename);
        String url = Joiner.on('/').join(parties);
        return url;
    }


    /**
     * create save path uri
     *
     * @param jarVo
     * @return
     */
    public static String createSavePath(JarVo jarVo) {
        List<String> parties = Lists.newArrayList(baseDir);
        parties.addAll(Arrays.asList(jarVo.getGroupId().split("\\.")));
        parties.add(jarVo.getAtifactId());
        parties.add(jarVo.getVersion());
        return Joiner.on('/').join(parties);
    }



    public static void main(String[] args) throws Exception {
        readJars().parallelStream().forEach(jarVo -> {
            String filename = jarVo.getAtifactId() + "-" + jarVo.getVersion() + "-sources.jar";
            String url = createUrl(jarVo);
            String path = createSavePath(jarVo);
            try {
                System.err.println("Downing " + url);
                downLoadFromUrl(url, filename, path);
                System.out.println("Downed " + url);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });

    }
}
